package com.freely.ui.viewModel;

import android.util.Log;

import com.freely.component.BaseViewModel;
import com.freely.data.database.FreelyDatabase;
import com.freely.data.entities.Group;
import com.freely.data.entities.User;
import com.freely.data.entities.UserGroupRelation;
import com.freely.data.network.FreelyClient;
import com.freely.data.network.ServerException;
import com.freely.data.network.requestEntities.RQUserId;
import com.freely.data.network.responseEntities.RSResult;
import com.freely.ui.util.ErrorUtil;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import io.reactivex.Single;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okio.ByteString;

public class HomeViewModel extends BaseViewModel {
    private static final String TAG = "HomeViewModel";
    private MutableLiveData<List<Group>> groupList = new MutableLiveData<>();
    private MutableLiveData<byte[]> headIcon = new MutableLiveData<>();
    private List<Group> groups = new ArrayList<>();

    public HomeViewModel() {
        groupList.setValue(groups);
    }

    //头像加载
    public void loadHeadIcon(long userId) {
        Single<User> userSingle = FreelyDatabase.getInstance().userDAO().queryUserByUserId(userId);
        Disposable disposable = userSingle.subscribeOn(Schedulers.io())
                .subscribe(user -> {
                    headIcon.postValue(ByteString.decodeBase64(user.getUserImage()).toByteArray());
                }, throwable -> {
                    ErrorUtil.dataReadErrorHint("头像读取错误", throwable);
                });
        register(disposable);
    }

    private void loadJoinedGroupList(@NonNull RQUserId userId) {
        //数据库读取
        Log.d(TAG, "loadJoinedGroupList: 开始加载已加入群列表");
        Single<List<Group>> listSingle = FreelyDatabase.getInstance()
                .groupDAO()
                .queryJoinedChatGroupList(userId.getUserId());

        Disposable disposable = listSingle.subscribeOn(Schedulers.io())
                .subscribe(groups -> {
                    Log.d(TAG, "loadJoinedGroupList: 从数据库加载");
                    Log.d(TAG, "loadJoinedGroupList: userId:" + userId.getUserId());
                    Log.d(TAG, "loadJoinedGroupList: list个数为：" + groups.size());
                    Log.d(TAG, "loadJoinedGroupList: list是否为空:" + groups.isEmpty());
                    if (!groups.isEmpty()) {
                        this.groups.clear();
                        this.groups.addAll(groups);
                        groupList.postValue(this.groups);
                        return;
                    }
                    Log.d(TAG, "loadJoinedGroupList: 从网络加载");
                    //网络读取
                    loadJoinedGroupListForInternet(userId);
                });
        register(disposable);

    }

	public void loadJoinedGroupListForInternet(@NonNull RQUserId userId) {
		Log.d(TAG, "loadJoinedGroupListForInternet: 网络加载");
        Single<RSResult<List<Group>,String>> single = FreelyClient.getFreelyService()
                .getJoinedGroupList(userId);
        Disposable disposable = single.subscribeOn(Schedulers.io())
                .subscribe(result -> {
                    if (!result.isResult()) {
                        ErrorUtil.errorHint(new ServerException(result.getFailure()));
                        return;
                    }
					Log.d(TAG, "loadJoinedGroupListForInternet: 加载成功");
                    List<Group> groups = result.getSuccess();
					Log.d(TAG, "loadJoinedGroupListForInternet: 组长度：" + groups.size());
					Log.d(TAG, "loadJoinedGroupListForInternet: this.groups.size = " + this
                            .groups.size());
					this.groups.clear();
                    this.groups.addAll(groups);
                    groupList.postValue(this.groups);

                    FreelyDatabase.getInstance().groupDAO().clearAllGroup();
                    FreelyDatabase.getInstance().groupDAO().insertGroup(groups);

                    List<UserGroupRelation> relations = new ArrayList<>();
                    for (Group g : groups) {
                        UserGroupRelation relation = new UserGroupRelation();
                        relation.setGroupId(g.getGroupId());
                        relation.setUserId(userId.getUserId());
                        relations.add(relation);
                    }
                    FreelyDatabase.getInstance().userGroupRelationDAO().clearAllRelation();
                    FreelyDatabase.getInstance()
                            .userGroupRelationDAO()
                            .insertUserGroupRelation(relations);

                },ErrorUtil::errorHint);
        register(disposable);
    }

    public MutableLiveData<List<Group>> getGroupList() {
        return groupList;
    }

    public MutableLiveData<byte[]> getHeadIcon() {
        return headIcon;
    }
}
